package com.sz.web.controller;

import com.sz.web.dao.DepartmentDao;
import com.sz.web.dao.EmployeeDao;
import com.sz.web.pojo.Department;
import com.sz.web.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
import java.util.Collection;

@Controller
public class EmployeeController {
    @Autowired
    EmployeeDao employeeDao;

    @Autowired
    DepartmentDao departmentDao;

    //展示员工列表
    @RequestMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeDao.getALL();
        model.addAttribute("emps",employees);//传递值
        return "emp/list";
    }

    //查询员工
    @GetMapping("/emp")
    public String toAAddpage(Model model){
        //查出所有部门
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments",departments);
        return "emp/add";
    }

    //添加员工
    @PostMapping("/emp")
    public String addEmp(Employee employee){
        System.out.println(employee);//输出一个员工
        employeeDao.save(employee);//添加一个员工
        return "redirect:/emps";
    }

    //删除员工
    @RequestMapping("/delete/{id}")
    public String updataEmp(@PathVariable("id") Integer id) {
        employeeDao.delete(id);
        return "redirect:/emps";
    }

    //编辑员工
    @RequestMapping("/update/{id}")
    public String updateEmp(@PathVariable("id") Integer id,Model model){
        //查出所有部门
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments",departments);
        //查出所有员工
        Employee employeeById = employeeDao.getEmployeeById(id);
        model.addAttribute("emp",employeeById);
        return "emp/update.html";
    }

    @RequestMapping("/user/loginout")
    public String loginout(HttpSession session){
        session.invalidate();//注销
        return "redirect:/main.html";
    }
}